<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        @submit.native.prevent
        :model="query"
        ref="queryForm"
        v-show="showSearch"
        :inline="true"
        label-width="65px"
      >
        <el-form-item label="巡检名称" prop="name">
          <common-input v-model="query.name" clearable @enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="query.status">
            <el-option label="全部" :value="null"></el-option>
            <el-option label="启用" value="0"></el-option>
            <el-option label="停用" value="1"></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="周期">
        <el-select
          v-model="query.cycle"
          placeholder="请选择"
          clearable

        >
          <el-option label="天" value="DAY"></el-option>
          <el-option label="周" value="WEEK"></el-option>
          <el-option label="月" value="MONTH"></el-option>
        </el-select>
      </el-form-item> -->

        <el-form-item label="创建时间" prop="daterange">
          <el-date-picker
            v-model="query.daterange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            align="right"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </common-search>
    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="edit(null)"
          v-hasPermi="['system:inspection:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="del(selectionIds.join(','), selectionRows)"
          v-hasPermi="['system:inspection:delete']"
          >批量删除
        </el-button>
      </el-col>
    </el-row>
    <common-table
      slot="content"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column
        label="巡检名称"
        align="left"
        prop="name"
        width="180"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">{{ row.name }}</template>
      </el-table-column>

      <!-- <el-table-column label="周期" align="left" prop="cycle">
        <template slot-scope="{ row }">{{ row.cycle }}</template>
      </el-table-column> -->

      <el-table-column
        label="巡检周期"
        align="left"
        prop="inspectionTime"
        show-overflow-tooltip
      >
        <template slot-scope="{ row }">{{
          translateToCN(row.inspectionTime)
        }}</template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        width="180"
      >
        <template slot-scope="{ row }">{{ row.createTime }}</template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="{ row }">
          <el-tag type="success" v-if="row.status == 0">启用</el-tag>
          <el-tag type="danger" v-else-if="row.status == 1">停用</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="left" width="220">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            @click="history(row)"
            v-hasPermi="['system:record:list']"
            >历史记录
          </el-button>
          <el-button type="text" @click="getInfo(row)">详情 </el-button>
          <el-button
            type="text"
            @click="edit(row)"
            v-hasPermi="['system:inspection:edit']"
            >编辑
          </el-button>
          <el-button
            type="text"
            @click="handleShake(row)"
            v-hasPermi="['system:inspection:status']"
            :disabled="row.isDisabledForShake"
          >
            <span v-if="row.status == 1">启用</span>
            <span v-if="row.status == 0">停用</span>
          </el-button>
          <el-button
            type="text"
            @click="del(row.id, [row])"
            v-hasPermi="['system:inspection:delete']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>
    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="query.pageNum"
      :limit.sync="query.pageSize"
      @pagination="getList"
    />

    <editDialog
      :alarmLevelArr="alarmLevelArr"
      :messageProprityArr="messageProprityArr"
      :patrolMachineArr="patrolMachineArr"
      :userList="userList"
      :columnList="columnList"
      ref="editDialog"
      @refresh="getList"
    />
    <detailDialog
      :alarmLevelArr="alarmLevelArr"
      :messageProprityArr="messageProprityArr"
      :patrolMachineArr="patrolMachineArr"
      :userList="userList"
      :columnList="columnList"
      ref="detailDialog"
    />
    <historyView
      v-if="showHistory"
      @back="showHistory = false"
      :inspectId="inspectId"
    />
  </common-list>
</template>

<script>
import editDialog from "./components/inspectAdd";
import detailDialog from "./components/inspectDetail";
import historyView from "./components/history";
import CommonList from "@/template/CommonList";
import {
  inspection_list,
  delete_inspection,
  delete_inspection_check,
  update_status,
  user_list,
  threshold_list,
} from "@/api/management/system/system.js";
import { getDicts } from "@/api/system/dict/data";
import BaseList from "@/mixins/BaseList";
import { translateToChinese } from "@/utils/cronExpParserUtil";
import { registerUpdateLifecycle } from "echarts";
import { getSingleArray } from "@/utils/util";

export default {
  components: { historyView, editDialog, detailDialog, CommonList },
  props: {},
  mixins: [BaseList],
  data() {
    return {
      showHistory: false,
      inspectId: "",
      filterMenu: "", //菜单筛选
      showSearch: true, // 查询部分显示
      total: 1, // 总条数
      loading: false, // table 加载中
      list: [], // 数据列
      selectionIds: "", // 列表选中数据id
      selectionRows: [],
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      query: {
        pageNum: 1,
        pageSize: 10,
        cycle: null,
        status: null,
        deptIds: null,
      }, // 查询条件
      isInfoDialog: false,
      info: {
        name: "测试",
        cycle: "DAY",
        inspectionTime: "15:40:55",
        businessPlateCheckedName: "工单",

        inspectionConfigList: [
          {
            beginTime: null,
            createBy: "admin",
            createTime: "2021-08-20 15:44:10",
            endTime: null,
            id: "301805568636358656",
            inspectionId: "301804928237441024",
            logic: "GT",
            name: "cpu",
            params: {},
            remark: "CPU负载",
            searchValue: null,
            threshold: 1,
            updateBy: null,
            updateTime: null,
          },
        ],
      },
      alarmLevelArr: [],
      messageProprityArr: [],
      patrolMachineArr: [],
      userList: [],
      columnList: [],
    };
  },
  watch: {},
  computed: {},
  methods: {
    translateToCN(val) {
      return translateToChinese(val);
    },
    getUserList() {
      user_list({ status: "0" }).then((res) => {
        this.userList = res.rows || [];
      });
    },

    getThresholdList() {
      threshold_list({ dictType: "INSPECT_THRESHOLD_INFOR_" }).then((res) => {
        this.columnList = res.data.reduce((r, c) => {
          r.push({ key: c.dictValue, label: c.dictLabel, isDisabled: false });
          return r;
        }, []);
      });
    },

    getDicts(v, n) {
      getDicts(v).then((res) => {
        if (res && res.code === 200) {
          if (n === 1) {
            // 1 告警等级   2  消息优先级  3  巡检机器
            this.alarmLevelArr = res.data;
          } else if (n === 2) {
            this.messageProprityArr = res.data;
          } else if (n === 3) {
            this.patrolMachineArr = res.data;
          }
        }
      });
    },
    /**
     * 选择
     */
    handleSelectionChange(selection) {
      this.selectionIds = selection.map((item) => item.id);
      this.selectionRows = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /**
     * 获取列表
     */
    getList() {
      this.loading = true;
      let query = { ...this.query };
      inspection_list(query)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.rows.reduce((r, c) => {
              r.push({
                ...c,
                isDisabledForShake: false,
              });
              return r;
            }, []);
            this.total = res.total;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /**
     * 查询
     */
    handleQuery() {
      if (!!this.query.daterange) {
        this.query.beginTime = this.query.daterange[0];
        this.query.endTime = this.query.daterange[1];
      } else {
        this.query.beginTime = "";
        this.query.endTime = "";
      }
      this.query.pageNum = 1;
      this.getList();
    },
    /**
     * 重置查询
     */
    resetQuery() {
      this.query = this.$options.data().query;
      this.$refs.commonDept.clearDept();
    },
    /**
     * 添加/编辑
     */
    edit(row) {
      // console.log(row);
      if (row && row.status === 0) {
        this.$GlobalErrorConfirm("编辑失败", "启用状态下不允许编辑");
      } else {
        if (row && row.alarmPeriod === "") {
          row.alarmFrequency = null;
        }
        this.$refs.editDialog.show(row ? { ...row } : {});
      }
    },
    /**
     * 详情
     */
    getInfo(row) {
      this.$refs.detailDialog.show(row ? { ...row } : {});
    },
    /**
     * 删除
     */
    del(ids, rows) {
      if (rows && rows.length) {
        let canDel = true;
        rows.map((v) => {
          if (v.status == 0) {
            canDel = false;
          }
        });
        if (!canDel) {
          this.$GlobalErrorConfirm("删除失败", "启用状态下不允许删除");
          return;
        }
      }
      this.$GlobalDeleteConfirm()
        .then(() => {
          delete_inspection_check({ ids: ids }).then((c_res) => {
            if (c_res && c_res.code === 200) {
              delete_inspection({ ids: ids }).then((d_res) => {
                if (d_res && d_res.code === 200) {
                  this.$GlobalSuccessMessage("删除成功");
                  if (
                    this.query.pageNum > 1 &&
                    ids.split(",").length === this.list.length
                  ) {
                    this.query.pageNum -= 1;
                  }
                  this.getList();
                } else {
                  this.$GlobalErrorConfirm("删除失败", d_res.msg);
                }
              });
            } else {
              this.$GlobalErrorConfirm("删除失败", c_res.msg);
            }
          });
        })
        .catch(() => {});
    },
    changeStatus(row) {
      return new Promise((resolve, reject) => {
        let status = row.status == 0 ? 1 : 0;
        update_status({ id: row.id, status: status })
          .then((res) => {
            if (res && res.code === 200) {
              this.getList();
              this.$GlobalSuccessMessage("操作成功");
              resolve(res);
            } else {
              this.$GlobalErrorConfirm("操作失败", res.msg).then();
              reject();
            }
          })
          .catch(() => reject());
      });
    },
    history(row) {
      this.showHistory = true;
      this.inspectId = row.id;
    },
  },
  created() {
    this.getList();
    this.getDicts("ALARM_LEVEL_", 1);
    this.getDicts("MESSAGE_PRIORITY_", 2);
    this.getDicts("SYS_INSPECTION_HOSTNAME_", 3);
    this.getUserList();
    this.getThresholdList();
  },
  mounted() {},
};
</script>
<style lang="scss" scoped></style>
